<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>所有事件数据</title>
    <link href="/api/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="/api/assets/css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .top-info {
            background-color: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            max-height: 1000px;
            overflow: hidden;
            transition: max-height 0.3s ease-out, margin-bottom 0.3s ease-out;
        }
        
        .top-info.collapsed {
            max-height: 0;
            margin-bottom: 0;
            padding: 0;
        }
        
        .float-button {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: none;
            padding: 10px 15px;
            background-color: #0d6efd;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.3s;
        }
        
        .logout-button {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            padding: 10px 15px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.3s;
        }
        
        .logout-button:hover {
            background-color: #bb2d3b;
        }
        
        .float-button:hover {
            background-color: #0b5ed7;
        }
        
        .toggle-button {
            background-color: #e9ecef;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .toggle-button:hover {
            background-color: #dee2e6;
        }
        
        .stats-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .stats-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #0d6efd;
        }
        
        .stats-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        @media (max-width: 768px) {
            .stats-container {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body class="container py-4">
    <button class="logout-button" onclick="logout()">
        <i class="bi bi-box-arrow-right"></i> 退出登录
    </button>
    <div class="top-info">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">所有事件数据</h4>
            <button class="toggle-button" onclick="toggleTopInfo()">
                <i class="bi bi-chevron-up"></i> 收起说明
            </button>
        </div>
        
        <div class="alert alert-info">
            <h5><i class="bi bi-info-circle"></i> 数据说明</h5>
            <ul class="mb-0">
                <li>此页面显示所有事件数据，包括已结算和未结算的记录</li>
                <li>数据每秒自动更新一次</li>
                <li>统计数据包括今日、昨日、本周和本月的汇总信息</li>
            </ul>
        </div>
        
        <!-- 添加用户卡片 -->
        <div id="userCard" class="card mb-3" style="display: none;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="card-title mb-1">当前用户信息</h5>
                        <p class="card-text mb-1">
                            <small class="text-muted">用户编号：</small>
                            <span id="userNickId">-</span>
                        </p>
                        <p class="card-text mb-1">
                            <small class="text-muted">用户昵称：</small>
                            <span id="userNickname">-</span>
                        </p>
                        <p class="card-text">
                            <small class="text-muted">用户状态：</small>
                            <span id="userStatus">-</span>
                        </p>
                    </div>
                    <div>
                        <button id="clearSearchBtn" class="btn btn-outline-secondary" onclick="clearSearch()">
                            <i class="bi bi-x-lg"></i> 清除搜索
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-12">
                <div class="input-group">
                    <span class="input-group-text">用户编号</span>
                    <input type="text" class="form-control" id="searchNickId" placeholder="输入用户编号搜索">
                    <span class="input-group-text">用户昵称</span>
                    <input type="text" class="form-control" id="searchNickname" placeholder="输入用户昵称搜索">
                    <button class="btn btn-primary" onclick="search()">搜索</button>
                    <button class="btn btn-outline-primary" onclick="fetchData()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新
                    </button>
                </div>
            </div>
        </div>
        <div class="row mb-3">
            <div class="col-md-12">
                <div class="input-group">
                    <span class="input-group-text">开始时间</span>
                    <input type="datetime-local" class="form-control" id="startTime">
                    <span class="input-group-text">结束时间</span>
                    <input type="datetime-local" class="form-control" id="endTime">
                    <button class="btn btn-primary" onclick="search()">查询</button>
                </div>
            </div>
        </div>
        
        <!-- 统计卡片部分 -->
        <div class="stats-section">
            <h4 class="mb-3">全部总览</h4>
            <div class="row stats-container g-2">
                <div class="col-md-3 col-sm-6">
                    <div class="stats-card">
                        <div class="stats-value" id="todayCount">0</div>
                        <div class="stats-label">今日数量</div>
                        <div class="stats-value" id="todayCost">¥0.00</div>
                        <div class="stats-label">今日金额</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stats-card">
                        <div class="stats-value" id="yesterdayCount">0</div>
                        <div class="stats-label">昨日数量</div>
                        <div class="stats-value" id="yesterdayCost">¥0.00</div>
                        <div class="stats-label">昨日金额</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stats-card">
                        <div class="stats-value" id="weekCount">0</div>
                        <div class="stats-label">本周数量</div>
                        <div class="stats-value" id="weekCost">¥0.00</div>
                        <div class="stats-label">本周金额</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stats-card">
                        <div class="stats-value" id="monthCount">0</div>
                        <div class="stats-label">本月数量</div>
                        <div class="stats-value" id="monthCost">¥0.00</div>
                        <div class="stats-label">本月金额</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <button class="float-button" onclick="toggleTopInfo()">
        <i class="bi bi-chevron-down"></i> 展开说明
    </button>
    
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>用户ID</th>
                    <th>用户昵称</th>
                    <th>系统分成</th>
                    <th>用户分成</th>
                    <th>总价值</th>
                    <th>用户状态</th>
                    <th>时间</th>
                    <th>nickId</th>
                </tr>
            </thead>
            <tbody id="eventTableBody">
            </tbody>
        </table>
    </div>
    
    <nav aria-label="Page navigation" class="d-flex justify-content-center mt-3">
        <ul class="pagination" id="pagination">
        </ul>
    </nav>

    <script src="/api/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        // 检查登录状态
        if (sessionStorage.getItem('isLoggedIn') !== 'true') {
            window.location.href = 'login.html';
        }

        function logout() {
            if (confirm('确定要退出登录吗？')) {
                sessionStorage.removeItem('isLoggedIn');
                window.location.href = 'login.html';
            }
        }

        let currentPage = 1;
        let pageSize = 10;
        let isTopInfoVisible = true;
        
        function toggleTopInfo() {
            const topInfo = document.querySelector('.top-info');
            const floatButton = document.querySelector('.float-button');
            const toggleButton = document.querySelector('.toggle-button');
            
            isTopInfoVisible = !isTopInfoVisible;
            
            if (isTopInfoVisible) {
                topInfo.classList.remove('collapsed');
                floatButton.style.display = 'none';
                toggleButton.innerHTML = '<i class="bi bi-chevron-up"></i> 收起说明';
            } else {
                topInfo.classList.add('collapsed');
                floatButton.style.display = 'block';
                toggleButton.innerHTML = '<i class="bi bi-chevron-down"></i> 展开说明';
                // 滚动到搜索框
                window.scrollTo({top: 0, behavior: 'smooth'});
            }
        }
        
        function clearStats() {
            document.getElementById('todayCount').textContent = '0';
            document.getElementById('todayCost').textContent = '¥0.00';
            document.getElementById('yesterdayCount').textContent = '0';
            document.getElementById('yesterdayCost').textContent = '¥0.00';
            document.getElementById('weekCount').textContent = '0';
            document.getElementById('weekCost').textContent = '¥0.00';
            document.getElementById('monthCount').textContent = '0';
            document.getElementById('monthCost').textContent = '¥0.00';
        }
        
        function updateStats(stats) {
            if (!stats) {
                clearStats();
                return;
            }
            
            const searchNickId = document.getElementById('searchNickId').value;
            const searchNickname = document.getElementById('searchNickname').value;
            
            // 更新总览卡片的标题
            const statsTitle = document.querySelector('.stats-section h4');
            if (statsTitle) {
                statsTitle.textContent = (searchNickId || searchNickname) ? '用户总览' : '全部总览';
            }
            
            document.getElementById('todayCount').textContent = stats.today.count;
            document.getElementById('todayCost').textContent = `¥${stats.today.total_cost?.toFixed(2) || '0.00'}`;
            document.getElementById('yesterdayCount').textContent = stats.yesterday.count;
            document.getElementById('yesterdayCost').textContent = `¥${stats.yesterday.total_cost?.toFixed(2) || '0.00'}`;
            document.getElementById('weekCount').textContent = stats.week.count;
            document.getElementById('weekCost').textContent = `¥${stats.week.total_cost?.toFixed(2) || '0.00'}`;
            document.getElementById('monthCount').textContent = stats.month.count;
            document.getElementById('monthCost').textContent = `¥${stats.month.total_cost?.toFixed(2) || '0.00'}`;
        }
        
        function updatePagination(total, current, size) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            const totalPages = Math.ceil(total / size);
            
            // 计算显示的页码范围
            let startPage = Math.max(1, current - 2);
            let endPage = Math.min(totalPages, current + 2);
            
            // 确保显示至少5个页码（如果有）
            while (endPage - startPage < 4 && endPage < totalPages) {
                endPage++;
            }
            while (endPage - startPage < 4 && startPage > 1) {
                startPage--;
            }
            
            // Previous button
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${current === 1 ? 'disabled' : ''}`;
            prevLi.innerHTML = `<a class="page-link" href="#" onclick="event.preventDefault(); goToPage(${current - 1})">&laquo;</a>`;
            pagination.appendChild(prevLi);
            
            // First page
            if (startPage > 1) {
                const firstLi = document.createElement('li');
                firstLi.className = 'page-item';
                firstLi.innerHTML = `<a class="page-link" href="#" onclick="event.preventDefault(); goToPage(1)">1</a>`;
                pagination.appendChild(firstLi);
                
                if (startPage > 2) {
                    const ellipsisLi = document.createElement('li');
                    ellipsisLi.className = 'page-item disabled';
                    ellipsisLi.innerHTML = '<a class="page-link">...</a>';
                    pagination.appendChild(ellipsisLi);
                }
            }
            
            // Page numbers
            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === current ? 'active' : ''}`;
                li.innerHTML = `<a class="page-link" href="#" onclick="event.preventDefault(); goToPage(${i})">${i}</a>`;
                pagination.appendChild(li);
            }
            
            // Last page
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsisLi = document.createElement('li');
                    ellipsisLi.className = 'page-item disabled';
                    ellipsisLi.innerHTML = '<a class="page-link">...</a>';
                    pagination.appendChild(ellipsisLi);
                }
                
                const lastLi = document.createElement('li');
                lastLi.className = 'page-item';
                lastLi.innerHTML = `<a class="page-link" href="#" onclick="event.preventDefault(); goToPage(${totalPages})">${totalPages}</a>`;
                pagination.appendChild(lastLi);
            }
            
            // Next button
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${current === totalPages ? 'disabled' : ''}`;
            nextLi.innerHTML = `<a class="page-link" href="#" onclick="event.preventDefault(); goToPage(${current + 1})">&raquo;</a>`;
            pagination.appendChild(nextLi);
        }
        
        function updateTable(records) {
            const tableBody = document.getElementById('eventTableBody');
            tableBody.innerHTML = '';
            
            if (!records || records.length === 0) {
                const tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="8" class="text-center">暂无数据</td>';
                tableBody.appendChild(tr);
                return;
            }
            
            records.forEach(record => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${record.openId || '-'}</td>
                    <td>${record.nickname || '-'}</td>
                    <td>¥${record.sysCost?.toFixed(2) || '0.00'}</td>
                    <td>¥${record.userCost?.toFixed(2) || '0.00'}</td>
                    <td>¥${record.totalCost?.toFixed(2) || '0.00'}</td>
                    <td>${record.status == 1 ? '正常' : '封禁'}</td>
                    <td>${record.createTime || '-'}</td>
                    <td>${record.nickId || '-'}</td>
                `;
                tableBody.appendChild(tr);
            });
        }
        
        function goToPage(page) {
            if (page < 1) return;
            currentPage = page;
            fetchData();
        }
        
        function search() {
            currentPage = 1;
            fetchData();
        }
        
        function clearSearch() {
            document.getElementById('searchNickId').value = '';
            document.getElementById('searchNickname').value = '';
            document.getElementById('startTime').value = '';
            document.getElementById('endTime').value = '';
            document.getElementById('userCard').style.display = 'none';
            currentPage = 1;
            fetchData();
        }
        
        function updateUserCard(records) {
            const userCard = document.getElementById('userCard');
            const searchNickId = document.getElementById('searchNickId').value;
            const searchNickname = document.getElementById('searchNickname').value;
            
            if ((searchNickId || searchNickname) && records && records.length > 0) {
                const user = records[0];
                document.getElementById('userNickId').textContent = user.nickId || '-';
                document.getElementById('userNickname').textContent = user.nickname || '-';
                document.getElementById('userStatus').textContent = user.userStatus === 1 ? '正常' : 
                    (user.userStatus === 0 ? '已封禁' : '-');
                userCard.style.display = 'block';
            } else {
                userCard.style.display = 'none';
            }
        }
        
        function fetchData() {
            let url = `/api/cost/all?page=${currentPage}&size=${pageSize}`;
            
            const searchNickId = document.getElementById('searchNickId').value;
            const searchNickname = document.getElementById('searchNickname').value;
            const startTime = document.getElementById('startTime').value;
            const endTime = document.getElementById('endTime').value;
            
            const params = new URLSearchParams();
            if (searchNickId) params.append('nickId', searchNickId);
            if (searchNickname) params.append('nickname', searchNickname);
            if (startTime) params.append('startTime', startTime.replace('T', ' ').replace(' ', ':00'));
            if (endTime) params.append('endTime', endTime.replace('T', ' ').replace(' ', ':00'));
            
            fetch(url + '&' + params.toString())
                .then(response => response.json())
                .then(data => {
                    console.log(data)
                    updateTable(data.records);
                    updatePagination(data.total, data.current, data.size);
                    updateStats(data.stats);
                    updateUserCard(data.records);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    //alert('获取数据失败，请刷新页面重试');
                });
        }
        
        function banUser(nickId) {
            if (!confirm('确定要封禁该用户吗？')) return;
            
            fetch(`/api/event/user/ban?nickId=${encodeURIComponent(nickId)}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    fetchData();
                }
            })
            .catch(error => {
                console.error('Error banning user:', error);
                alert('操作失败，请重试');
            });
        }
        
        function unbanUser(nickId) {
            if (!confirm('确定要解封该用户吗？')) return;
            
            fetch(`/api/event/user/unban?nickId=${encodeURIComponent(nickId)}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    fetchData();
                }
            })
            .catch(error => {
                console.error('Error unbanning user:', error);
                alert('操作失败，请重试');
            });
        }
        
        function showSettleModal(nickId) {
            // 创建模态框
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.id = 'settleModal';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">结算设置</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">选择结算时间范围：</label>
                                <select class="form-select" id="settleDays">
                                    <option value="today">今天</option>
                                    <option value="yesterday">昨天</option>
                                    <option value="week">本周</option>
                                </select>
                            </div>
                            <div id="customDateRange" style="display: none;">
                                <div class="mb-3">
                                    <label class="form-label">开始时间：</label>
                                    <input type="datetime-local" class="form-control" id="settleStartTime">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">结束时间：</label>
                                    <input type="datetime-local" class="form-control" id="settleEndTime">
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="settleUserConfirm('${nickId}')">确定</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 监听下拉框变化
            const bsModal = new bootstrap.Modal(modal);
            modal.querySelector('#settleDays').addEventListener('change', function(e) {
                const customDiv = modal.querySelector('#customDateRange');
                customDiv.style.display = e.target.value === 'custom' ? 'block' : 'none';
            });
            
            // 显示模态框
            bsModal.show();
            
            // 模态框关闭时删除
            modal.addEventListener('hidden.bs.modal', function() {
                document.body.removeChild(modal);
            });
        }
        
        function settleUserConfirm(nickId) {
            const modal = document.getElementById('settleModal');
            const daysSelect = modal.querySelector('#settleDays');
            let startTime, endTime;
            
            // 获取当前时间，并调整到北京时间
            const now = new Date();
            const utc8Offset = 8 * 60; // UTC+8 偏移分钟数
            const localOffset = now.getTimezoneOffset(); // 本地时区偏移分钟数
            const totalOffset = utc8Offset + localOffset; // 需要调整的总分钟数
            
            // 调整到北京时间
            const beijingNow = new Date(now.getTime() + totalOffset * 60 * 1000);
            const today = new Date(beijingNow.getFullYear(), beijingNow.getMonth(), beijingNow.getDate());
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            
            // 计算本周的开始时间（从周一开始）
            const weekStart = new Date(today);
            weekStart.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
            
            // 格式化日期时间的函数
            function formatDateTime(date, withTime = true) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                if (withTime) {
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                }
                return `${year}-${month}-${day}`;
            }
            
            switch (daysSelect.value) {
                case 'today':
                    startTime = formatDateTime(today, false) + ' 00:00:00';
                    endTime = formatDateTime(beijingNow);
                    break;
                case 'yesterday':
                    startTime = formatDateTime(yesterday, false) + ' 00:00:00';
                    endTime = formatDateTime(yesterday, false) + ' 23:59:59';
                    break;
                case 'week':
                    startTime = formatDateTime(weekStart, false) + ' 00:00:00';
                    endTime = formatDateTime(beijingNow);
                    break;
                case 'custom':
                    startTime = modal.querySelector('#settleStartTime').value;
                    endTime = modal.querySelector('#settleEndTime').value;
                    
                    if (!startTime || !endTime) {
                        alert('请选择开始和结束时间');
                        return;
                    }
                    
                    startTime = startTime.replace('T', ' ') + ':00';
                    endTime = endTime.replace('T', ' ') + ':00';
                    break;
                default:
                    alert('请选择有效的时间范围');
                    return;
            }
            
            fetch('/api/event/user/settle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `nickId=${encodeURIComponent(nickId)}&startTime=${encodeURIComponent(startTime)}&endTime=${encodeURIComponent(endTime)}`
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    bootstrap.Modal.getInstance(modal).hide();
                    fetchData();
                }
            })
            .catch(error => {
                console.error('Error settling user:', error);
                alert('结算失败，请重试');
            });
        }
        
        // 初始加载
        fetchData();
    </script>
</body>
</html> 